//
//  UITextVeiw + Extension.swift
//  microBlog
//
//  Created by apple on 16/5/3.
//  Copyright © 2016年 Hill. All rights reserved.
//

import UIKit

extension UITextView {
    
    
    // 将表情图片转换成表情字符串，以发送到新浪微博
    var emoticonText: String? {
        
        var result = ""
        
        let attr = self.attributedText
//        遍历自身的富文本
        attr.enumerateAttributesInRange(NSMakeRange(0, attr.length), options: []) { (dict, range, _) -> Void in
            
            if let attribute = dict["NSAttachment"] as? WEXTextAttachment {
                
//                是表情，取到描述表情的字符串
                result += attribute.emoticon?.chs ?? ""
                
                
            }else{
//                不是表情
                result += (attr.string as NSString).substringWithRange(range)
            }
            
        }
        
        return result
        
    }
    
    // 插入表情字符
    func insertEmoticon(emoticon: WEXEmoticonModel){
//        将现有文字生成一个NSMutableAttributedString
        let originalAttr = NSMutableAttributedString(attributedString: self.attributedText)
        
//        获取图片路径
        let image = UIImage(named: "\(emoticon.folderName ?? "")/\(emoticon.png ?? "")",inBundle: WEXEmoticonKeyBoardViewModel.sharedViewModel.emoticonBundle,compatibleWithTraitCollection: nil )
        
//        获取数据模型
        let attachment = WEXTextAttachment()
//        给属性赋值
        attachment.emoticon = emoticon
        attachment.image = image
        
//        附件高度
        let attachmentHW = self.font!.lineHeight
        
        attachment.bounds = CGRect(x: 0, y: -4, width: attachmentHW, height: attachmentHW)
        
//        生成富文本字符串
        let attr = NSAttributedString(attachment: attachment)
        
//        获取选择范围
        var selectedRange = self.selectedRange
        
        originalAttr.replaceCharactersInRange(selectedRange, withAttributedString: attr)
        
//        设置字体大小
        originalAttr.addAttribute(NSFontAttributeName, value: self.font!, range: NSMakeRange(0, originalAttr.length))
//        设置完成搞得富文本赋值
        self.attributedText = originalAttr
        
//        设置每次添加内容，光标跟着后移
        selectedRange.location += 1
        
        selectedRange.length = 0
        
//        将选择范围重新赋值
        self.selectedRange = selectedRange
        
//        将文字改变的通知发送给控制器
        NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: self)
        
//        调用文字改变的代理方法
        delegate?.textViewDidChange!(self)
        
        
    }
    
    


}